package cvi.com.reader.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cvi.com.reader.R;
import cvi.com.reader.activity.PersonalActivity;
import cvi.com.reader.activity.PictureWorksDetailsAcitivity;
import cvi.com.reader.activity.WorksDetailsAcitivity;
import cvi.com.reader.adapter.PictureBookAdapter;
import cvi.com.reader.base.BaseFragment;
import cvi.com.reader.bean.CategoriesBean;
import cvi.com.reader.bean.HotBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.UtilsOnclickListen;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyGridView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/7/22.
 * 绘本
 */

public class PictureBookFragment extends BaseFragment implements View.OnClickListener, PictureBookAdapter.CollectListener {

    @BindView(R.id.fragment_name)
    TextView fragmentName;
    @BindView(R.id.user_info)
    LinearLayout userInfo;
    @BindView(R.id.gridview)
    MyGridView gridview;
    Unbinder unbinder;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    private PictureBookAdapter pictureBookAdapter = null;
    //诗词大会，首页，课本，绘本，文学巨匠
    private List<CategoriesBean.RowsBean> rowsBeanList = new ArrayList<CategoriesBean.RowsBean>();
    private int has_children = -1;
    private int pid = -1;
    //首页宫格数据包含热门数据
    private List<HotBean.RowsBean> homeList = new ArrayList<HotBean.RowsBean>();
    private MyReceiver myReceiver;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_picture_book;
    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    protected void initData() {

        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getPictureBookData(pid).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {

                    @Override
                    protected void onSuccess(JSONObject response) {
                        getData(response);
                        smartRefreshLayout.finishRefresh(true);
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    }
                });
    }

    @Override
    protected void initView() {
        initSmartRefreshLayout();
        stateView.getBackground().setAlpha(153);
        userInfo.setOnClickListener(this);
        fragmentName.setText("绘本");
        if (Hawk.contains("categoriesBeanList")) {
            rowsBeanList = Hawk.get("categoriesBeanList");
        }
        if (rowsBeanList != null) {
            for (int i = 0; i < rowsBeanList.size(); i++) {
                if ("绘本".equals(rowsBeanList.get(i).getName())) {
                    pid = rowsBeanList.get(i).getId();
                    has_children = rowsBeanList.get(i).getHas_children();


                }
            }
        }
    }

    private void getData(JSONObject response) {
        JSONArray array = response.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            HotBean.RowsBean rowsBean = (HotBean.RowsBean) JSONObject.toJavaObject(object, HotBean.RowsBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            homeList.add(rowsBean);
        }
        if (homeList != null) {
            pictureBookAdapter = new PictureBookAdapter(getActivity(), homeList);
            gridview.setAdapter(pictureBookAdapter);
            pictureBookAdapter.setCollectListener(this);
            pictureBookAdapter.notifyDataSetChanged();
            gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    HotBean.RowsBean rowsBean = (HotBean.RowsBean) adapterView.getAdapter().getItem(i);
                    Hawk.put("WorksDetails", rowsBean);
                    if ("0".equals(rowsBean.getType())) {
                        Intent intent = new Intent(getActivity(), WorksDetailsAcitivity.class);
                        startActivity(intent);
                    } else if ("1".equals(rowsBean.getType())) {
                        Intent intent = new Intent(getActivity(), PictureWorksDetailsAcitivity.class);
                        startActivity(intent);
                    }


                }
            });
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(constant.TAB_MYRECEIVER);
        getActivity().registerReceiver(myReceiver, intentFilter);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (myReceiver != null) {
            getActivity().unregisterReceiver(myReceiver);
        }
    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(getActivity()));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(getActivity(), "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                homeList.clear();
                initData();
            }
        });

    }

    @Override
    public void onCollectClick(String flag, int id) {

        if ("1".equals(flag)) {
            //绑定生命周期,获取宫格数据
            NetWorkManager.getInstance().getNetWorkApiService().setCollect(id).compose(this.<JSONObject>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                        @Override
                        protected void onSuccess(JSONObject response) {
                            //收藏之后，重新请求数据，清空元数据
                            homeList.clear();
                            initData();

                        }
                    });

        } else {
            //绑定生命周期,获取宫格数据
            NetWorkManager.getInstance().getNetWorkApiService().removeCollect(id).compose(this.<JSONObject>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                        @Override
                        protected void onSuccess(JSONObject response) {
                            //收藏之后，重新请求数据，清空元数据
                            homeList.clear();
                            initData();

                        }
                    });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_info:
                if (UtilsOnclickListen.isFastClick()) {
                go(PersonalActivity.class);}
                break;
        }
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            homeList.clear();
            initData();
        }
    }
}
